<script setup>
import {nextTick, onMounted, ref} from "vue";
import {ElMessage, ElNotification} from "element-plus";
import {addDept, deleteDept, getDeptList, updateDept} from "@/api/dept.js";

const userList = ref([])
const addUserDrawer = ref(false)
const updateUserDrawer = ref(false)
const newDept = ref({
  name: '',
  description: '',
  username: ''
})

const updateDeptData = ref({
  departmentId: '',
  username: '',
  name: '',
  description: ''
})

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref();

const pageForm = ref({
  page: currentPage.value,
  size: pageSize.value
})

const handleCurrentChange = (page) => {
  currentPage.value = page;
  pageForm.value.page = page;
  // 在这里可以触发数据加载逻辑
  console.log('当前页码:', page);
  getDeptListAll()
};

const getDeptListAll = async () => {
  const list = await getDeptList(pageForm.value)
  console.log(list)
  if (list.code !== 200) {
    ElNotification({
      title: '接口错误',
      message: '获取用户列表失败！',
      type: 'error',
    })
  }
  userList.value = list.data.records
  total.value = list.data.total
  pageSize.value = list.data.size
  currentPage.value = list.data.current
}
const openAddUserDrawer = () => {
  addUserDrawer.value = true
}

const openUpdateUserDrawer = (data) => {
  updateUserDrawer.value = true
  updateDeptData.value = data
}

const saveNewUser = async () => {
  if (newDept.value.name === '') {
    ElMessage.error('部门名称不能为空！')
    return
  }
  if (newDept.value.description === '') {
    ElMessage.error('部门描述不能为空！')
    return
  }
  const result = await addDept(newDept.value)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '添加部门成功！',
      type: 'success',
    })
    newDept.value = {}
    addUserDrawer.value = false
    await nextTick()
    await getDeptListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '添加用户失败！',
      type: 'error',
    })
  }
}

const deleteUserById = async (id) => {
  const result = await deleteDept(id)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '删除用户成功！',
      type: 'success',
    })
    await getDeptListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '删除用户失败！',
      type: 'error',
    })
  }
}

async function updateUserById() {
  const result = await updateDept(updateDeptData.value)
  if (result.code === 200) {
    ElNotification({
      title: '请求成功',
      message: '修改用户信息成功！',
      type: 'success',
    })
    updateUserDrawer.value = false
    await getDeptListAll()
  } else {
    ElNotification({
      title: '请求失败',
      message: '修改用户信息失败！',
      type: 'error',
    })
  }
}


onMounted(async () => {
  await getDeptListAll()
})

const userRole = JSON.parse(localStorage.getItem('userInfo')).role


</script>

<template>
  <div class="user-operation" v-if="userRole === 1">
    <el-button type="primary" size="default" @click="openAddUserDrawer">添加部门</el-button>
    <!-- 添加用户 -->
    <el-drawer v-model="addUserDrawer" title="添加部门" :with-header="true">
      <div class="add-user-item">
        <span class="input-label">部门名称: </span>
        <el-input v-model="newDept.name" placeholder="请输入部门名称"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">部门描述: </span>
        <el-input v-model="newDept.description" placeholder="请输入部门描述"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">负责人: </span>
        <el-input v-model="newDept.username" placeholder="请输入部门负责人"></el-input>
      </div>
      <div class="add-user-item">
        <el-button class="add-user-btn" type="primary" size="default" @click="saveNewUser">添加部门</el-button>
      </div>
    </el-drawer>
    <!-- 修改用户 -->
    <el-drawer v-model="updateUserDrawer" title="修改部门" :with-header="true">
      <div class="add-user-item">
        <span class="input-label">部门名称: </span>
        <el-input v-model="updateDeptData.name" placeholder="请修改部门名称"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">负责人: </span>
        <el-input v-model="updateDeptData.username" placeholder="请修改负责人"></el-input>
      </div>
      <div class="add-user-item">
        <span class="input-label">部门描述: </span>
        <el-input v-model="updateDeptData.description" placeholder="请修改部门描述"></el-input>
      </div>
      <div class="add-user-item">
        <el-button class="add-user-btn" type="primary" size="default" @click="updateUserById">修改信息</el-button>
      </div>
    </el-drawer>
  </div>
  <div class="user-list">
    <el-table
        :data="userList"
        border
        class="user-table"
    >
      <el-table-column prop="departmentId" label="部门ID" align="center" width="100"/>
      <el-table-column prop="name" label="部门名称" align="center" min-width="100" max-width="150"/>
      <el-table-column prop="username" label="负责人" align="center" width="100"></el-table-column>
      <el-table-column prop="description" label="部门描述" align="center" min-width="200"/>
      <el-table-column prop="createdTime" label="创建时间" align="center" min-width="150" max-width="200"/>
      <el-table-column prop="updatedTime" label="更新时间" align="center" min-width="150" max-width="200"/>
      <el-table-column label="操作" align="center" width="200" v-if="userRole === 1">
        <template #default="scope">
          <div class="operation-btns">
            <el-button type="success" size="small" @click="openUpdateUserDrawer(scope.row)">修改</el-button>
            <el-button type="danger" size="small"
                       @click="deleteUserById(scope.row.departmentId)">删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px; text-align: center">
      <el-pagination
          :page-size="pageSize"
          :total="total"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
      />
    </div>
  </div>
</template>

<style scoped>
.user-operation {
  margin-bottom: 20px;
}

.user-table {
  position: relative;
}

.add-user-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-label {
  margin-right: 10px;
  width: 100px;
  text-align: right;
  font-weight: bold;
  color: #606266;
}

.add-user-btn {
  width: 100%;
  margin-top: 50px;
}

.operation-btns {
  display: flex;
  justify-content: center;
}

</style>
